package util;

import entity.Paper;
import entity.Subject;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

/** OwnStorage 个人编写数据存储工具 */
public class OwnStorage {
  /**
   * saveStorage 将 Paper 中的数据 存储到 txt 文件
   *
   * @param paper 试卷数据
   * @throws IOException 创建文件失败
   */
  public static void saveStorage(Paper paper) throws IOException {
    String path = "./Result/" + paper.getOwner() + "/";
    File root = new File(path);
    if (!root.exists()) {
      boolean isDone = root.mkdirs();
      if (!isDone) {
        throw new IOException();
      }
    }
    String fileName = paper.getTime() + ".txt";
    File file = new File(path, fileName);
    final FileWriter fileWriter = new FileWriter(file);
    List<Subject> subjects = paper.getSubjects();
    subjects.forEach(
        (item) -> {
          try {
            fileWriter.write(item.toString());
          } catch (IOException e) {
            e.printStackTrace();
          }
        });
    fileWriter.flush();
    fileWriter.close();
  }
}
